<template>
  <section class="container mx-auto px-4 py-8">
    <div class="bg-white rounded-xl shadow-md p-6">
      <h2 class="text-2xl font-bold text-blue-800 mb-6">行程规划</h2>
      
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <!-- 左侧输入面板 -->
        <div class="space-y-4">
          <div class="bg-gray-50 p-4 rounded-lg">
            <div class="space-y-3">
              <input
                v-model="startPoint"
                type="text"
                placeholder="输入起点位置"
                class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500"
              >
              <input
                v-model="endPoint"
                type="text"
                placeholder="输入终点位置"
                class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500"
              >
              <div class="flex space-x-2">
                <button
                  v-for="mode in travelModes"
                  :key="mode.value"
                  @click="selectedMode = mode.value"
                  :class="[
                    'flex-1 px-4 py-2 rounded-lg',
                    selectedMode === mode.value 
                      ? 'bg-blue-600 text-white' 
                      : 'bg-gray-100 hover:bg-gray-200'
                  ]"
                >
                  {{ mode.label }}
                </button>
              </div>
              <button
                @click="planRoute"
                class="w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700 transition-all"
              >
                开始规划路线
              </button>
            </div>
          </div>
        </div>

        <!-- 右侧地图容器 -->
        <div class="md:col-span-2">
          <div id="map-container" class="h-[500px] rounded-lg overflow-hidden"></div>
          <div id="route-panel" class="mt-4 bg-white p-4 rounded-lg shadow-md max-h-64 overflow-y-auto"></div>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { debounce } from 'lodash-es'

// 高德地图类型声明
declare const AMap: any

const startPoint = ref('')
const endPoint = ref('')
const selectedMode = ref('driving')
const mapInstance = ref<any>(null)
const routePlanner = ref<any>(null)
const mapLoaded = ref(false)

const travelModes = [
  { label: '驾车', value: 'driving' },
  { label: '步行', value: 'walking' },
  { label: '公交', value: 'transit' }
]

// 初始化地图
const initMap = () => {
  if (!mapInstance.value) {
    mapInstance.value = new AMap.Map('map-container', {
      resizeEnable: true,
      center: [107.627701, 34.347382],
      zoom: 13,
      viewMode: '2D'
    })
  }
}

// 加载高德API
const loadAMapScript = () => {
  return new Promise<void>((resolve) => {
    if (window.AMap) {
      mapLoaded.value = true
      return resolve()
    }

    window._AMapSecurityConfig = {
      securityJsCode: '746a86ffcc388980961bdfc5fb9097fb'
    }

    const script = document.createElement('script')
    script.src = `https://webapi.amap.com/maps?v=1.4.15&key=aea9cc042a0024a91cc095349d5fa49a&plugin=AMap.Driving,AMap.Walking,AMap.Transfer`
    script.onload = () => {
      mapLoaded.value = true
      resolve()
    }
    document.head.appendChild(script)
  })
}

// 路径规划方法
const planRoute = debounce(async () => {
  if (!startPoint.value || !endPoint.value) {
    alert('请输入起点和终点')
    return
  }

  if (!mapLoaded.value) {
    await loadAMapScript()
  }

  // 清除旧路线
  if (routePlanner.value) {
    routePlanner.value.clear()
  }

  // 创建对应交通方式实例
  const options = {
    map: mapInstance.value,
    panel: 'route-panel'
  }

  switch (selectedMode.value) {
    case 'driving':
      routePlanner.value = new AMap.Driving(options)
      break
    case 'walking':
      routePlanner.value = new AMap.Walking(options)
      break
    case 'transit':
      routePlanner.value = new AMap.Transfer(options)
      break
  }

  // 执行路径搜索
  routePlanner.value.search([
    { keyword: startPoint.value, city: '宝鸡' },
    { keyword: endPoint.value, city: '宝鸡' }
  ], (status: string, result: any) => {
    if (status !== 'complete') {
      alert('路线规划失败: ' + (result?.info || '未知错误'))
    }
  })
}, 300)

// 生命周期管理
onMounted(async () => {
  await loadAMapScript()
  initMap()
})

onBeforeUnmount(() => {
  if (routePlanner.value) {
    routePlanner.value.clear()
  }
  if (mapInstance.value) {
    mapInstance.value.destroy()
    mapInstance.value = null
  }
})
</script>

<style scoped>
#map-container {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

#route-panel {
  scrollbar-width: thin;
  scrollbar-color: #3b82f6 #f1f5f9;
}

#route-panel::-webkit-scrollbar {
  width: 8px;
}

#route-panel::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 4px;
}

#route-panel::-webkit-scrollbar-thumb {
  background-color: #3b82f6;
  border-radius: 4px;
}
</style>